# -*- coding: utf-8 -*-
import sys
import logging
from lxml import etree
from xadmin.model import *
from xadmin.lib.base import *

from authkit.authorize.pylons_adaptors import authorize, authorized
from authkit.permissions import RemoteUser, ValidAuthKitUser

log = logging.getLogger(__name__)

class ProjectsController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    # To properly map this controller, ensure your config/routing.py file has
    # a resource setup:
    #     map.resource('project', 'projects')

    def index(self, format='html'):
        """GET /projects: All items in the collection."""
        # url_for('projects')
        c.projects = Session.query(Project).all()
        response.headers['content-type'] = 'text/xml; charset=utf-8'
        return render('/projects/list.mako')

    def create(self):
        """POST /projects: Create a new item."""
        # url_for('projects')
        try:
            log.debug('Creando proyecto')
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            if not content:
                content = request.params.get('xml')
            doc = etree.fromstring(content.encode("utf8"))
            #parseramos el doc
            name = doc.xpath('/project/name')[0].text
            description = doc.xpath('/project/description')[0].text
            client = doc.xpath('/project/client')[0].text
            start = doc.xpath('/project/start')[0].text
            end = doc.xpath('/project/end')[0].text
            #Guardamos el proyecto
            project = Project(name, description, client)
            project.start = start
            project.end = end
            Session.save(project)
            Session.commit()
            del response.headers['Content-Type']
            response.headers['Location'] = '/projects/%s' % project.id
            response.status_code = 201
            return
        except:
            print "ERROR: ", sys.exc_info()[0]
            abort(400)

    def new(self, format='html'):
        """GET /projects/new: Form to create a new item."""
        # url_for('new_project')
        pass

    def update(self, id):
        """PUT /projects/id: Update an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(h.url_for('project', id=ID),
        #           method='put')
        # url_for('project', id=ID)
        try:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            doc = etree.fromstring(content)
            project = Session.query(Project).get(id)
            name = None
            if project:
                name = doc.xpath('/project/name')
                if name:
                    project.name = name[0].text
                description = doc.xpath('/project/description')
                if description:
                    project.description = description[0].text
                client = doc.xpath('/project/client')
                if client:
                    project.client = client[0].text
                start = doc.xpath('/project/start')
                if start:
                    project.start = start[0].text
                end = doc.xpath('/project/end')
                if end:
                    project.end = end[0].text
                #Session.save(project)
                Session.commit()
                response.headers['Content-Type'] = 'text/xml; charset=utf-8'
                response.headers['Location'] = '/projects/%s' % project.id
                return
            else:
                abort(404)
        except:
            abort(400)

    def delete(self, id):
        """DELETE /projects/id: Delete an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(h.url_for('project', id=ID),
        #           method='delete')
        # url_for('project', id=ID)
        project = Session.query(Project).get(id)
        if project:
            Session.delete(project)
            Session.commit()
        del response.headers['Content-Type']
        response.status_code = 204
        return

    def show(self, id, format='html'):
        """GET /projects/id: Show a specific item."""
        # url_for('project', id=ID)
        c.project = Session.query(Project).get(id)
        if c.project:
            response.headers['Content-Type'] = 'text/xml; charset=utf-8'
            return render('/projects/view.mako')
        else:
            abort(404)

    def edit(self, id, format='html'):
        """GET /projects/id;edit: Form to edit an existing item."""
        # url_for('edit_project', id=ID)
        pass
